import { reactive, readonly } from "vue"

function usePromise() {
	const initState = {
		isLoading: false
	}
	const state = reactive(initState)
	const fallback = (promise) => {
		if(state.isLoading) {
			return new Promise()
		}
		state.isLoading = true
		if(promise instanceof Function) {
			return new Promise((resolve, reject) => {
				promise().then(result => {
					state.isLoading = false
					return resolve(result)
				}, error => {
					state.isLoading = false
					return reject(error)
				})
			})
		} else {
			return promise.finally(() => {
				state.isLoading = false
			})
		}
	}
	initState.fallback = fallback
	return readonly(state)
}

export default usePromise